//
//  DoctorReserveMenuView.swift
//  EyeVisionForPatients
//
//  Created by PMC on 2020/2/28.
//  Copyright © 2020 tao Tao. All rights reserved.
//

import UIKit
import HandyJSON

struct DoctorReserveMenu: HandyJSON {
    var code: String = ""
    var name: String = ""
}

class DoctorReserveMenuView: UIView {
    
    var clickedClosure: ((_ code: String, _ name: String?) -> Void)?
    
    var cancelClosure: (() -> Void)?
    
    private var type: DoctorReserveTopViewType = .department
    
    private var menuOffices = [DoctorReserveMenu]() {
        didSet {
            tableView.reloadData()
        }
    }
    
    private var menuDepartments = [Department]() {
        didSet {
            tableView.reloadData()
        }
    }

    @IBOutlet private weak var maskBgView: UIView! {
        didSet {
            maskBgView.alpha = 0.0
            
            let tap = UITapGestureRecognizer(target: self, action: #selector(dismissMenu))
            tap.delegate = self
            maskBgView.addGestureRecognizer(tap)
        }
    }

    @IBOutlet weak var contentViewHConstraint: NSLayoutConstraint! {
        didSet {
            contentViewHConstraint.constant = 0.0
        }
    }
    
    @IBOutlet weak var activityView: UIActivityIndicatorView!
    
    @IBOutlet private weak var contentView: UIView!
    
    @IBOutlet private var tableView: UITableView! {
        didSet {
            tableView.delegate = self
            tableView.dataSource = self
            tableView.rowHeight = 44
            tableView.estimatedRowHeight = UITableView.automaticDimension
            tableView.backgroundColor = .white
            tableView.tableFooterView = UIView()
            tableView.register(DoctorReserveMenuCell.nibForCell(),
                               forCellReuseIdentifier: DoctorReserveMenuCell.reuseIdentifier())
        }
    }
    
    func show(in view: UIView, type: DoctorReserveTopViewType) {
        self.type = type
        view.addSubview(self)
        layoutIfNeeded()
        
        switch type {
        case .department:
            self.contentViewHConstraint.constant = 308.0
        case .doctorType:
            self.contentViewHConstraint.constant = 179.0
        case .office:
            self.contentViewHConstraint.constant = 220.0
        default:
            self.contentViewHConstraint.constant = 135.0
        }
        
        UIView.animate(withDuration: 0.25, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 1.0, options: .layoutSubviews, animations: {
            self.maskBgView.alpha = 1.0
            self.layoutIfNeeded()
        }) { _ in
            switch type {
            case .department:
                self.loadDepartmentData()
            case .office:
                self.loadOfficeData()
            case .doctorType:
                self.loadDoctorTypeData()
            case .prescription:
                self.loadPrescriptionData()
            }
        }
    }
    
    func dismiss() {
        layoutIfNeeded()
        self.contentViewHConstraint.constant = 0.0
        
        UIView.animate(withDuration: 0.25, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 1.0, options: .layoutSubviews, animations: {
            self.maskBgView.alpha = 0.0
            self.layoutIfNeeded()
        }) { _ in
            self.removeFromSuperview()
        }
    }
}

extension DoctorReserveMenuView: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return type == .department ? menuDepartments.count : menuOffices.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: DoctorReserveMenuCell.reuseIdentifier(),
                                                 for: indexPath) as! DoctorReserveMenuCell
        switch type {
        case .department:
            let model = menuDepartments[indexPath.row]
            cell.configure(with: model.name)
        default:
            let model = menuOffices[indexPath.row]
            cell.configure(with: model.name)
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        dismiss()
        var code = ""
        var name: String?
        switch type {
        case .department:
            let model = menuDepartments[indexPath.row]
            code = "\(model.id ?? "")"
            name = model.name
        default:
            let model = menuOffices[indexPath.row]
            code = model.code
            name = model.name
        }
        clickedClosure?(code, name)
    }
}

// MARK: - 数据
private extension DoctorReserveMenuView {
    /// 全部科室
    func loadDepartmentData() {
        activityView.startAnimating()
        DepartmentViewModel.getDepartmentList(success: { models in
            self.activityView.stopAnimating()
            var tempModels = models
            let model = Department(id: "", name: "全部")
            tempModels.insert(model, at: 0)
            self.menuDepartments = tempModels
        }) { errorMsg in
            self.activityView.stopAnimating()
            HUDTool.showError(message: errorMsg)
        }
    }
    
    /// 医生职称
    func loadOfficeData() {
        activityView.startAnimating()
        let paras = ["category": "doc_job_title"]
        HttpTool.shared.request(target: ApiManager.doctorReserveMenu(paras: paras), success: { (json, code) in
            switch code {
            case .failure:
                self.activityView.stopAnimating()
                HUDTool.showError(message: json["message"].description)
            case .success:
                self.activityView.stopAnimating()
                if var models = JSONDeserializer<DoctorReserveMenu>.deserializeModelArrayFrom(json: json["data"].description) as? [DoctorReserveMenu] {
                    let model = DoctorReserveMenu(code: "", name: "全部")
                    models.insert(model, at: 0)
                    self.menuOffices = models
                } else {
                    HUDTool.showError(message: "请求数据发生错误，稍后重试")
                }
            }
        }) { errorMsg in
            HUDTool.showError(message: errorMsg)
        }
    }
    
    /// 服务类型筛选
    func loadDoctorTypeData() {
        let data = [
            ["code": "0", "name": "全部"],
            ["code": "1", "name": "图文咨询"],
            ["code": "3", "name": "云门诊"],
            ["code": "4", "name": "门诊挂号"]
        ]
        
        if let models = JSONDeserializer<DoctorReserveMenu>.deserializeModelArrayFrom(array: data) as? [DoctorReserveMenu] {
            self.menuOffices = models
        }
    }
    
    /// 处方筛选
    func loadPrescriptionData() {
        let data = [
            ["code": "", "name": "全部"],
            ["code": "1", "name": "有"],
            ["code": "0", "name": "无"]
        ]
        if let models = JSONDeserializer<DoctorReserveMenu>.deserializeModelArrayFrom(array: data) as? [DoctorReserveMenu] {
            self.menuOffices = models
        }
    }
    
    @objc private func dismissMenu() {
        dismiss()
        cancelClosure?()
    }
}

extension DoctorReserveMenuView: UIGestureRecognizerDelegate {
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        if let touchClass = touch.view?.classForCoder,
            touchClass != maskBgView.classForCoder {
            return false
        }
        return true
    }
}
